package com.example.hcd.functionactivity;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.example.hcd.R;
import com.example.hcd.datamanage.BorrowData;
import com.example.hcd.datamanage.PeopleNextData;
import com.example.hcd.datamanage.UserInfo;
import com.example.hcd.internet.LinkHelp;
import com.example.hcd.internet.URLS;
import com.example.hcd.tool.DigitalTool;
import com.example.hcd.tool.ToastHelp;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.Selection;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

public class BorrowApply extends BaseActivity implements OnClickListener {

	private BorrowApply context;

	private View main_view;

	private LayoutInflater inflater;

	private EditText amoutEdit;

	private EditText bigAmout;

	private BorrowData borrowData;



	// 获取下一步处理人
	private ArrayList<PeopleNextData> peoples_next;
	private TextView nextPeople;
	private RelativeLayout nextPeopleBg;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		mPageName = "BorrowApply";
		inflater = LayoutInflater.from(this);
		context = this;
		main_view = inflater.inflate(R.layout.borrow_apply_view, null);
		setContentView(main_view);

		initview();
	}

	private int MIN_MARK = 0;
	private int MAX_MARK = 100000000;

	private void initview() {
		// 借款申請人
		EditText applyEdit = (EditText) findViewById(R.id.editText2);
		applyEdit.setText(UserInfo.getUserInfor().getName());

		borrowData = new BorrowData(null);
		// 返回键
		ImageView backBtn = (ImageView) findViewById(R.id.title_bar_btn_left);
		// 提交键
		ImageView uploadBtn = (ImageView) findViewById(R.id.title_bar_btn_right);
		backBtn.setOnClickListener(context);
		uploadBtn.setOnClickListener(context);

		// 金额
		amoutEdit = (EditText) findViewById(R.id.editText3);
		bigAmout = (EditText) findViewById(R.id.editText4);

		amoutEdit.setOnEditorActionListener(new OnEditorActionListener() {

			@Override
			public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
				// TODO Auto-generated method stub
				return false;
			}
		});

		amoutEdit.addTextChangedListener(new TextWatcher() {
			private boolean isChanged = false;

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(amoutEdit.getText().toString().equals("."))
				{
					return;
				}
				if (isChanged) {// ----->如果字符未改变则返回
					return;
				}
				String str = s.toString();

				isChanged = true;
				String cuttedStr = str;
				boolean flag = false;
				/* 删除字符串中的dot */
				for (int i = str.length() - 1; i >= 0; i--) {
					char c = str.charAt(i);
					if ('.' == c && i == str.length() - 4) {
						cuttedStr = str.substring(0, i + 3);
						if (cuttedStr.endsWith(".")) {
							cuttedStr = cuttedStr.substring(0, i + 1);
						}
						flag = true;
						break;
					}
				}

				if (flag) {
					amoutEdit.setText(cuttedStr);
					 //设置新光标所在的位置
					 Selection.setSelection((Editable)amoutEdit.getText(),
					 cuttedStr.length());
				}

				str = amoutEdit.getText().toString();
				if (str.contains(".")) {
					int numlength = 0;
					for (int i = 0; i < str.length() - 1; i++) {
						char c = str.charAt(i);
						if (c == '.') {
							break;
						} else {
							numlength++;
						}

					}
					if (numlength > 8) {
						int index = amoutEdit.getSelectionStart();
						Editable editable = amoutEdit.getText();
						editable.delete(index - 1, index);
					}

				} else {
					if (str.length() > 8) {
						int index = amoutEdit.getSelectionStart();
						Editable editable = amoutEdit.getText();
						editable.delete(index - 1, index);
					}
				}

				if (amoutEdit.getText().toString() == null || amoutEdit.getText().toString().equals("")) {
					str = "0";
				} else {
					str = amoutEdit.getText().toString();

				}
				Double numOfmoney = Double.parseDouble(str);

				bigAmout.setText(DigitalTool.toBigMode(numOfmoney));
				borrowData.setAmount(""+numOfmoney);

				isChanged = false;
			}
		});
		// 获取下一步处理人
		nextPeopleBg = (RelativeLayout)main_view.findViewById(R.id.next_people_bg);
		nextPeople = (TextView) main_view.findViewById(R.id.next_people);
		peoples_next = new ArrayList<PeopleNextData>();
		// 获取下一步处理人
		getNextPeople next = new getNextPeople();
		next.execute();

	}

	// 获取下一步处理人
	private class getNextPeople extends AsyncTask<String, Integer, String> {

		// private ProgressDialog mProgress;
		public getNextPeople() {
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {
				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("taskId", ""));
				response = LinkHelp.post(URLS.getNextWorkUser("borrow"), vs, false);

				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			
			if(result==null)
			{
				ToastHelp.doToast(context, "网络异常！");
				return;
			}
			
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(result);
				if (jsonObject.isNull("code")) {
					String status = jsonObject.getString("status");
					if (status.equals("success")) {
						{
							if (result.contains("workUserInfo")) {
								JSONArray peoples = jsonObject.getJSONArray("workUserInfo");
								for (int i = 0; i < peoples.length(); i++) {
									PeopleNextData data = new PeopleNextData();
									JSONObject myJS = peoples.getJSONObject(i);
									data.setUserId(myJS.getString("userId"));
									data.setUserName(myJS.getString("userName"));
									data.setDepartmentId(myJS.getString("departmentId"));
									data.setDepartmentName(myJS.getString("departmentName"));
									data.setCompanyId(myJS.getString("companyId"));
									data.setCompanyName(myJS.getString("companyName"));
									data.setIsHead(myJS.getString("isHead"));
									data.setCode(myJS.getString("code"));
									peoples_next.add(data);
								}
								if (peoples_next.size() >= 1) {
									nextPeople.setText(peoples_next.get(0).getUserName() + "("
											+ peoples_next.get(0).getDepartmentName() + ")");
								}else
								{
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("noNeedWorkUserId")) {
								if (jsonObject.getString("noNeedWorkUserId").equals("true")) {
									nextPeople.setText("下一步不需要处理人");
									nextPeopleBg.setVisibility(View.GONE);
								}

							} else if (result.contains("msg")) {
								nextPeople.setText(jsonObject.getString("msg"));
								
								if(jsonObject.getString("msg").contains("不需要"))
                    			{
                    				nextPeopleBg.setVisibility(View.GONE);
                    			}
								
							} else {
								System.out.println("Shit!服务器给的什么破数据");
							}

						}

					} else {
						String msg = jsonObject.getString("msg");
						//Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
						ToastHelp.doToastInTop(context, msg);
						nextPeople.setText("空");
						nextPeopleBg.setVisibility(View.GONE);
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		// //隐藏软键盘
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(main_view.getWindowToken(), 0);

		switch (id) {
		case R.id.title_bar_btn_left:
			finish();
			break;

		case R.id.title_bar_btn_right:
			upload();
			break;
		default:
			break;
		}
	}

	private void upload() {
		if (isCanUpload()) {
			UpdateLoadInfo upload = new UpdateLoadInfo(borrowData);
			upload.execute();
		}
	}

	/*
	 * 传送数据到服务器
	 */
	private class UpdateLoadInfo extends AsyncTask<String, Integer, String> {
		BorrowData borrowData;

		// private ProgressDialog mProgress;
		public UpdateLoadInfo(BorrowData borrowData) {

			this.borrowData = borrowData;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(String... params) {
			String result = null;
			HttpResponse response = null;
			BufferedReader reader = null;
			try {

				ArrayList<NameValuePair> vs = new ArrayList<NameValuePair>();
				vs.add(new BasicNameValuePair("title", borrowData.getTitle()));
				vs.add(new BasicNameValuePair("bankName", borrowData.getBank()));
				vs.add(new BasicNameValuePair("bankCardld", borrowData.getNumofbank()));
				vs.add(new BasicNameValuePair("amount", "" + borrowData.getAmount()));

				EditText edit = (EditText) main_view.findViewById(R.id.editText6);
				vs.add(new BasicNameValuePair("reason",
						edit.getText().toString() == null ? "" : edit.getText().toString()));
				response = LinkHelp.post(URLS.getBorrowStart(), vs, false);

				if (response != null) {
					StatusLine line = response.getStatusLine();
					if (line.getStatusCode() == 200) {
						reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
						StringBuilder sb = new StringBuilder();
						for (String s = reader.readLine(); s != null; s = reader.readLine()) {
							sb.append(s);
						}
						reader.close();
						
						result = sb.toString();

						System.out.println(result);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(result);
				if (jsonObject.isNull("code")) {
					String status = jsonObject.getString("status");
					UserInfo info = UserInfo.getUserInfor();
					if (status.equals("success")) {
						Toast.makeText(context, "提交成功", Toast.LENGTH_SHORT).show();

						finish();
					} else {
						String msg = jsonObject.getString("msg");
						//Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
						ToastHelp.doToastInTop(context, msg);
					}

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

	}

	public boolean isCanUpload() {
		EditText title = (EditText) findViewById(R.id.editText);
		String titleStr = title.getText().toString();
		if (titleStr == null || titleStr.equals("")) {
			//Toast.makeText(context, "标题不能为空", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "标题不能为空");
			return false;
		} else {
			borrowData.setTitle(titleStr);
		}

		titleStr = amoutEdit.getText().toString();
		if (titleStr.equals(".")||Double.parseDouble(titleStr) <= 0.00000000001) {
			//Toast.makeText(context, "金额输入错误", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "金额输入错误");
			return false;
		} else {
			borrowData.setAmount(titleStr);
		}
		title = (EditText) findViewById(R.id.editText5);
		titleStr = title.getText().toString();
		if (titleStr.equals("") || titleStr == null) {
			//Toast.makeText(context, "请填写借款方式", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "请填写开户银行");
			return false;
		} else {
			borrowData.setBank(titleStr);
		}
		
		title = (EditText) findViewById(R.id.editText51);
		titleStr = title.getText().toString();
		if (titleStr.equals("") || titleStr == null) {
			//Toast.makeText(context, "请填写借款方式", Toast.LENGTH_SHORT).show();
			ToastHelp.doToastInTop(context, "请填写银行账号");
			return false;
		} else {
			borrowData.setNumofbank(titleStr);
		}

		return true;
	}

}
